use salvo::prelude::*;
use std::sync::Arc;
use tracing::{error, info, instrument};
use utils::response::*;

use crate::api::model::auth::*;
use crate::rpc::client::SystemRpcClient;
use crate::rpc::pb::auth as rpc_auth;

/// 获取验证码
#[endpoint(
    operation_id = "system_auth_getCaptcha",
    tags("系统/注册登录"),
    responses(
        (status_code = 200, description = "成功"),
    )
)]
#[instrument(skip(req))]
pub async fn get_captcha(req: &mut Request) -> Result<Json<ApiResponse<GetCaptchaRes>>, AppError> {
    info!("API: 获取验证码请求");

    // 获取 RPC 客户端
    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| AppError::internal("RPC 客户端未初始化"))?;

    // 创建 RPC 请求
    let rpc_req = rpc_auth::GetCaptchaReq {
        uuid: "".to_string(),
    };

    // 调用 RPC 服务
    match rpc_client.get_captcha(rpc_req).await {
        Ok(rpc_response) => {
            info!("API: RPC 调用成功");
            let rpc_res = rpc_response.into_inner();

            let response = GetCaptchaRes {
                uuid: rpc_res.uuid,
                captcha_img: rpc_res.captcha_img,
            };

            Ok(Json(ApiResponse::success_with_message(
                response,
                "验证码获取成功",
            )))
        }
        Err(status) => {
            error!("API: RPC 调用失败: {:?}", status);
            Err(AppError::from_tonic_status(status))
        }
    }
}

/// 账号登录
#[endpoint(
    operation_id = "system_auth_loginByAccount",
    tags("系统/注册登录"),
    request_body = LoginReq,
    responses(
        (status_code = 200, description = "登录成功"),
        (status_code = 400, description = "请求参数错误"),
        (status_code = 401, description = "认证失败"),
        (status_code = 500, description = "服务器错误")
    )
)]
#[instrument(skip(req))]
pub async fn login_by_account(req: &mut Request) -> Result<Json<ApiResponse<LoginRes>>, AppError> {
    info!("API: 账号登录请求");

    // 解析请求体
    let body = req.parse_json::<LoginReq>().await.map_err(|e| {
        error!("API: 解析请求体失败: {:?}", e);
        AppError::validation("请求体格式错误")
    })?;

    info!("API: 用户登录 - username: {}", body.username);

    // 获取 RPC 客户端
    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| AppError::internal("RPC 客户端未初始化"))?;

    // 转换为 RPC 请求
    let rpc_req = rpc_auth::LoginByAccountReq {
        username: body.username.clone(),
        password: body.password,
        invite_code: "".to_string(),
        captcha_uuid: body.uuid.unwrap_or_default(),
        captcha_code: body.captcha.unwrap_or_default(),
    };

    // 调用 RPC 服务并转换响应
    match rpc_client.login_by_account(rpc_req).await {
        Ok(rpc_response) => {
            info!("API: RPC 调用成功");
            let rpc_res = rpc_response.into_inner();

            if let Some(login_model) = rpc_res.login_model {
                let response = LoginRes {
                    access_token: login_model.access_token,
                    refresh_token: login_model.refresh_token,
                    access_expire: login_model.access_expire,
                    user_info: UserInfo {
                        id: login_model.id,
                        username: login_model.username,
                        nickname: login_model.nickname,
                        avatar: login_model.avatar,
                    },
                };
                Ok(Json(ApiResponse::success_with_message(
                    response,
                    "登录成功",
                )))
            } else {
                Err(AppError::unauthorized())
            }
        }
        Err(status) => {
            error!("API: RPC 调用失败: {:?}", status);
            Err(AppError::from_tonic_status(status))
        }
    }
}
